package com.h3c.ptability.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eos.common.util.IdWorker;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.h3c.ptability.cache.UserCache;
import com.h3c.ptability.entity.PtMenu;
import com.h3c.ptability.entity.PtRoleMenu;
import com.h3c.ptability.mapper.PtMenuMapper;
import com.h3c.ptability.mapper.PtRoleMenuMapper;
import com.h3c.ptability.service.CommService;
import com.h3c.ptability.service.IPtRoleMenuService;
import com.h3c.ptability.dto.PtRoleMenuDTO;
import com.h3c.ptability.utils.InitExampleOrderByUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Copyright (C), 2020-2020, h3c
 * FileName: PtRoleMenuServiceImpl
 *
 * @Author: l22886
 * @Date: 2022-03-14
 * Description: pt_role_menu serviceImpl
 * Version: 1.0
 */
@Slf4j
@Service
public class PtRoleMenuServiceImpl extends ServiceImpl<PtRoleMenuMapper, PtRoleMenu> implements IPtRoleMenuService {

    @Resource
    private PtRoleMenuMapper ptRoleMenuMapper;

    @Resource
    private PtMenuMapper ptMenuMapper;

    @Autowired
    private CommService commService;

    /**
     * @title: selectFuzzyByDto
     * @description: 模糊查询操作
     * @params: [ dto ]
     * @return: java.util.List
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public List<PtRoleMenuDTO> selectFuzzyByDto(PtRoleMenuDTO dto) {
        //List<PtRoleMenu> list = ptRoleMenuMapper.selectByExample(initFuzzyExample(dto));
        List<PtRoleMenu> list = ptRoleMenuMapper.queryListByFuzzy(JSONObject.parseObject(JSONObject.toJSONString(dto),PtRoleMenu.class));
        return JSONArray.parseArray(JSONArray.toJSONString(list), PtRoleMenuDTO.class);
    }

    /**
     * @title: selectByDto
     * @description: 精确查询操作
     * @params: [ dto ]
     * @return: java.util.List
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public List<PtRoleMenuDTO> selectByDto(PtRoleMenuDTO dto) {
        //List<PtRoleMenu> list = ptRoleMenuMapper.selectByExample(initExample(dto));
        List<PtRoleMenu> list = ptRoleMenuMapper.queryList(JSONObject.parseObject(JSONObject.toJSONString(dto),PtRoleMenu.class));
        return JSONArray.parseArray(JSONArray.toJSONString(list), PtRoleMenuDTO.class);
    }

    /**
     * @title: insertDto
     * @description: 插入操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer insertDto(PtRoleMenuDTO dto) {
        //if (null == dto.getId() || "".equals(dto.getId())) {
        //    String pkId = idWorker.nextId() + "";
        //    dto.setId(pkId);
        //}
        return ptRoleMenuMapper.insertPtRoleMenu(JSONObject.parseObject(JSON.toJSONString(dto), PtRoleMenu.class));
    }

    /**
     * @title: updateDto
     * @description: 修改操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer updateDto(PtRoleMenuDTO dto) {
        //if (null != dto && null != dto.getId() && !"".equals(dto.getId())) {
            return ptRoleMenuMapper.updatePtRoleMenu(JSONObject.parseObject(JSON.toJSONString(dto), PtRoleMenu.class));
            //return ptRoleMenuMapper.updateByPrimaryKey(JSONObject.parseObject(JSON.toJSONString(dto), PtRoleMenu.class));
        //} else {
        //    return 0;
        //}
    }

    /**
     * @title: deleteDto
     * @description: 删除操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer deleteDto(PtRoleMenuDTO dto) {
        //if (null != dto && null != dto.getId() && !"".equals(dto.getId())) {
            return ptRoleMenuMapper.deletePtRoleMenu(JSONObject.parseObject(JSON.toJSONString(dto), PtRoleMenu.class));
            //return ptRoleMenuMapper.deleteByPrimaryKey(dto.getId());
        //} else {
        //    return 0;
        //}
    }

    @Override
    public Map<String, Object> getRoleMenuDate(String appId, String roleId) {
        Map<String, Object> result = new HashMap<>();

        //树形菜单
        QueryWrapper<PtMenu> menuQW = new QueryWrapper<>();
        menuQW.lambda().eq(PtMenu::getAppId, appId).orderByAsc(PtMenu::getSortId);
        List<PtMenu> menus = ptMenuMapper.selectList(menuQW);
        //菜单通过父类分组
        Map<String, List<Map<String, Object>>> menuMap = menus.stream().filter(o -> !"-1".equals(o.getParentItemId())).map(o -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", o.getItemId());
            map.put("label", o.getItemName());
            map.put("parentId", o.getParentItemId());
            return map;
        }).collect(Collectors.groupingBy(o -> (String) o.get("parentId")));
        //顶级菜单
        List<Map<String, Object>> parentMenu = menus.stream()
                .filter(o -> "-1".equals(o.getParentItemId())).map(o -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", o.getItemId());
                    map.put("label", o.getItemName());
                    return map;
                }).collect(Collectors.toList());
        //设置子节点
        parentMenu.forEach(o -> setChildren(o, menuMap));

        //角色拥有的菜单
        QueryWrapper<PtRoleMenu> roleQW = new QueryWrapper<>();
        roleQW.lambda().eq(PtRoleMenu::getItemAppId, appId).eq(PtRoleMenu::getRoleId, roleId);
        List<PtRoleMenu> roleMenus = ptRoleMenuMapper.selectList(roleQW);
        List<String> roleMenu = roleMenus.stream().map(PtRoleMenu::getItemId).collect(Collectors.toList());

        //结果
        result.put("appMenu", parentMenu);
        result.put("roleMenu", roleMenu);
        return result;
    }

    @Override
    @Transactional
    public Integer editRoleMenuData(String appId, String roleId, String itemIds) {
        QueryWrapper<PtRoleMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PtRoleMenu::getItemAppId, appId).eq(PtRoleMenu::getRoleId, roleId);
        ptRoleMenuMapper.delete(queryWrapper);
        Date now = new Date();
        String userNameAndId = UserCache.getLoginUserNameAndId();
        List<PtRoleMenu> list = new ArrayList<>();
        Stream.of(itemIds.split(",")).forEach(itemId -> {
            PtRoleMenu roleMenu = new PtRoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setItemAppId(appId);
            roleMenu.setItemId(itemId);
            roleMenu.setCreateTime(now);
            roleMenu.setCreatorId(userNameAndId);
            list.add(roleMenu);
        });
        boolean b = saveBatch(list);
        return b ? 1 : 0;
    }

    private void setChildren(Map<String, Object> parent, Map<String, List<Map<String, Object>>> menuMap) {
        String id = (String) parent.get("id");
        List<Map<String, Object>> children = menuMap.get(id);
        if (children != null) {
            children.forEach(o -> setChildren(o, menuMap));
            parent.put("children", children);
        }
    }


    /**
     * @title: initFuzzyExample
     * @description: 初始化 模糊查询 example
     * @params: [ dto ]
     * @return: tk.mybatis.mapper.entity.Example
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    private Example initFuzzyExample(PtRoleMenuDTO dto) {
        Example example = InitExampleOrderByUtils.initExampleOrderBy(PtRoleMenu.class, dto.getOrderBy());
        Example.Criteria criteriaName = example.createCriteria();
        if (null != dto) {
            if (null != dto.getRoleId() && !"".equals(dto.getRoleId())) {
                criteriaName.andLike("RoleId", "%" + dto.getRoleId() + "%");
            }
            if (null != dto.getItemId() && !"".equals(dto.getItemId())) {
                criteriaName.andLike("ItemId", "%" + dto.getItemId() + "%");
            }
            if (null != dto.getItemAppId() && !"".equals(dto.getItemAppId())) {
                criteriaName.andLike("ItemAppId", "%" + dto.getItemAppId() + "%");
            }
            if (null != dto.getCreateTime() && !"".equals(dto.getCreateTime())) {
                criteriaName.andLike("CreateTime", "%" + dto.getCreateTime() + "%");
            }
            if (null != dto.getCreatorId() && !"".equals(dto.getCreatorId())) {
                criteriaName.andLike("CreatorId", "%" + dto.getCreatorId() + "%");
            }
        }
        return example;
    }

    /**
     * @title: initExample
     * @description: 初始化 精确查询 example
     * @params: [ dto ]
     * @return: tk.mybatis.mapper.entity.Example
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    private Example initExample(PtRoleMenuDTO dto) {
        Example example = InitExampleOrderByUtils.initExampleOrderBy(PtRoleMenu.class, dto.getOrderBy());
        Example.Criteria criteriaName = example.createCriteria();
        if (null != dto) {
            if (null != dto.getRoleId() && !"".equals(dto.getRoleId())) {
                criteriaName.andEqualTo("RoleId", dto.getRoleId());
            }
            if (null != dto.getItemId() && !"".equals(dto.getItemId())) {
                criteriaName.andEqualTo("ItemId", dto.getItemId());
            }
            if (null != dto.getItemAppId() && !"".equals(dto.getItemAppId())) {
                criteriaName.andEqualTo("ItemAppId", dto.getItemAppId());
            }
            if (null != dto.getCreateTime() && !"".equals(dto.getCreateTime())) {
                criteriaName.andEqualTo("CreateTime", dto.getCreateTime());
            }
            if (null != dto.getCreatorId() && !"".equals(dto.getCreatorId())) {
                criteriaName.andEqualTo("CreatorId", dto.getCreatorId());
            }
        }
        return example;
    }


}
